<?php
class OLM_Zencart_Categories
{
	static function getZencartCategoriesToSelectFormat($website)
	{
		$ret = array();
		foreach ($website as $w)
		{
			$categories = OLM_Zencart_Categories::getWebsiteCategoriesById($w['id']);
			$ret[$w['id']] = array('name' => $w['name'], 'children' => OLM_Zencart_Categories::buildCategoriesFormat($categories));
		}
		return $ret;
	}

	static function getWebsiteCategoriesById($website_id)
	{
		$data = file_get_contents(Q::ini('custom_system/zencart_categories_dir') . "website{$website_id}");
		$cat_data_array = (unserialize($data));
		return $cat_data_array;
	}
	
	static function buildCategoriesFormat($categories)
	{
		$cat_1 = Helper_BSS_Array::Search($categories, 'parent_id', 0);
		$temp_1 = array();
		foreach ($cat_1 as $c1)
		{
			$temp_1[$c1['categories_id']]['name'] = $c1['categories_name'];
			$cat_2 = Helper_BSS_Array::Search($categories, 'parent_id', $c1['categories_id']);
			$temp_2 = array();
			foreach ($cat_2 as $c2)
			{
				$temp_2[$c2['categories_id']]['name'] = $c2['categories_name'];
				$cat_3 = Helper_BSS_Array::Search($categories, 'parent_id', $c2['categories_id']);
				$temp_3 = array();
				foreach ($cat_3 as $c3)
				{
					$temp_3[$c3['categories_id']]['name'] = $c3['categories_name'];
				}
				$temp_2[$c2['categories_id']]['children'] = $temp_3;
			}
			$temp_1[$c1['categories_id']]['children'] = $temp_2;
		}
		return $temp_1;
	}
	
	static function getChildrenIdById($categories_id, $website_id)
	{
		$categories_data = OLM_Zencart_Categories::GetWebsiteCategoriesById($website_id);
		$children = Helper_BSS_Array::Search($categories_data, 'parent_id', $categories_id);
		return $children;
	}
	
	static function getAncestorIdById($categories_id, $website_id, $categories_data=array())
	{
		if ( ! $categories_data)
		{
			$categories_data = OLM_Zencart_Categories::GetWebsiteCategoriesById($website_id);
		}
		$categories = Helper_BSS_Array::Search($categories_data, 'categories_id', $categories_id);
		$categories = array_shift($categories);
		if ($categories['parent_id'] != 0)
		{
			$temp = OLM_Zencart_Categories::getAncestorIdById($categories['parent_id'], $website_id, $categories_data);
			array_push($temp, $categories['categories_id']);
			return $temp;
		}
		else
		{
			return array($categories['categories_id']);
		}
	}
	
	static function getOffspringIdById($categories_id, $website_id, $categories_data=array())
	{
		if ( ! $categories_data)
		{
			$categories_data = OLM_Zencart_Categories::GetWebsiteCategoriesById($website_id);
		}
		$children = Helper_BSS_Array::Search($categories_data, 'parent_id', $categories_id);
		if ( ! $children)
		{
			return array($categories_id);
		}
		$ret = array();
		foreach ($children as $c)
		{
			$temp = OLM_Zencart_Categories::GetOffspringIdById($c['categories_id'], $website_id, $categories_data);
			foreach ($temp as $t)
			{
				$ret[] = $t;
			}
		}
		$ret[] = $categories_id;
		return $ret;
	}
}